package storage.metadata;

import java.util.*;

import storage.record.*;
import storage.tx.*;

public class StatMgr {
	private TableMgr tblmgr;
	private Map<String,StatInfo> tablestats;
	private int numcalls;
	
	public StatMgr(TableMgr tblmgr, Transaction tx){
		this.tblmgr = tblmgr;
		refreshStatistics(tx);
	}
	
	public synchronized StatInfo getStatInfo(String tblname, TableInfo ti, Transaction tx){
		numcalls ++;
		if (numcalls > 100)
			refreshStatistics(tx);
		StatInfo si = tablestats.get(tblname);
		if (si == null){
			si = calcTableStats(ti, tx);
			tablestats.put(tblname, si);
		}
		return si;
	}
	
	private synchronized void refreshStatistics(Transaction tx){
		tablestats = new HashMap<String, StatInfo>();
		numcalls = 0;
		TableInfo tcatmd = tblmgr.getTableInfo("tblcat", tx);
		RecordFile tcatfile = new RecordFile(tcatmd, tx);
		while(tcatfile.next()){
			String tblname = tcatfile.getString("tblname");
			TableInfo md = tblmgr.getTableInfo(tblname, tx);
			StatInfo si = calcTableStats(md, tx);
			tablestats.put(tblname, si);
		}
		tcatfile.close();
	}
	
	private synchronized StatInfo calcTableStats(TableInfo ti, Transaction tx){
		int numRecs = 0;
		RecordFile rf = new RecordFile(ti, tx);
		while(rf.next()){
			numRecs++;
		}
		int blknum = rf.currentRid().blocknum();
		rf.close();
		int numblocks = 1 + blknum;
		return new StatInfo(numblocks, numRecs);
	}
}
